package com.alibaba.csp.sentinel.dashboard.rule.zookeeper;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.RuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleDrive;
import com.alibaba.csp.sentinel.util.AssertUtil;

public class AbsractDynamicRuleDrive<T extends RuleEntity> implements DynamicRuleDrive<T> {

	@Autowired
	private ZookeeperOptUtil opt;
	
	private Class<T> clazz;
	
	@SuppressWarnings("unchecked")
	public AbsractDynamicRuleDrive() {
		Type genType = this.getClass().getGenericSuperclass();
		Type [] params = ((ParameterizedType)genType).getActualTypeArguments();
		clazz = (Class<T>) params[0];
	}
	
	@Override
	public void publish(String app, List<T> rules) throws Exception {
		AssertUtil.notEmpty(app, "app name cannot be empty");
		opt.publish(app, rules, clazz);
	}

	@Override
	public List<T> getRules(String app) throws Exception {
		List<T> rules = opt.getRules(app, clazz);
		return rules;
	}

}
